package com.wstuo.multitenancy;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.hibernate.cfg.Environment;
import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl;

/**
 * 
 * @author will
 *
 */
public class ConnectionProviderBuilder {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ConnectionProviderBuilder.class);

	public static final String DRIVER = "dataSource.driverClassName";
	public static final String URL = "dataSource.url";
	public static final String USER = "dataSource.username";
	public static final String PASS = "dataSource.password";
	public static final String SERVERNAME="dataSource.serverName";
	
	public static DriverManagerConnectionProviderImpl buildConnectionProvider() {
		DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
		InputStream inputStream = null;
		inputStream = ConnectionProviderBuilder.class.getClassLoader().getResourceAsStream("hibernate.properties");
		Properties prop = new Properties();
		try {
			prop.load(inputStream);
		} catch (IOException e) {
			logger.error("Properties load unsuccess", e); 
		}
		Properties connectionProps = new Properties();
		connectionProps.put( Environment.DRIVER, prop.getProperty(DRIVER) );
		connectionProps.put( Environment.URL, prop.getProperty(URL).replace("${"+SERVERNAME+"}", prop.getProperty(SERVERNAME)) );
		connectionProps.put( Environment.USER, prop.getProperty(USER) );
		connectionProps.put( Environment.PASS, prop.getProperty(PASS) );
		connectionProvider.configure( connectionProps);
		
		return connectionProvider;
	}


}
